package com.nhn.ssi.util;

import java.io.Reader;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class SqlMapFactory {

	private static SqlMapClient sqlMap;
	private static SqlMapFactory instance;
	private static Logger logger = Logger.getLogger(SqlMapFactory.class);

	private SqlMapFactory() throws Exception {
		if (sqlMap == null) {
			Reader reader = null;
			try {
//				String resource = "datasource/config/SqlMapConfig.xml";
//				reader = Resources.getResourceAsReader(resource);

				// 通过spring注入获得sqlmap
				BeanFactory factory = new ClassPathXmlApplicationContext(
						"*.xml");

				// 得到UserService具体实现，用于操作业务逻辑
				sqlMap = (SqlMapClient) factory.getBean("sqlMapClient");
				// sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
			} catch (Exception e) {
				logger.error(e.getMessage());
				throw e;
			} finally {
//				reader.close();
			}
		}
	}

	/**
	 * 获取SqlMapClient对象
	 * 
	 * @return
	 */
	public static SqlMapClient getSqlMap() {
		if (instance == null) {
			try {
				instance = new SqlMapFactory();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sqlMap;
	}

}
